#include "characterfeaturesform.h"
#include "ui_characterfeaturesform.h"
#include "featuredelegate.h"


CharacterFeaturesForm::CharacterFeaturesForm(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::CharacterFeaturesForm)
{
    ui->setupUi(this);

    m_featureModel = new FeatureTableModel(this);

    m_sortFilter = new QSortFilterProxyModel(this);
    m_sortFilter->setSourceModel(m_featureModel);


    ui->tableView->setModel(m_sortFilter);
    ui->tableView->setItemDelegate(new FeatureDelegate(this));
}

CharacterFeaturesForm::~CharacterFeaturesForm()
{
    delete ui;
}

void CharacterFeaturesForm::setSourceModel(DTwentyModel *sourceModel)
{
    Q_UNUSED(sourceModel)
}

void CharacterFeaturesForm::setCampaign(Campaign *campaign)
{
    m_featureModel->setCampaign(campaign);

//    ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
}

void CharacterFeaturesForm::addCharacterClass()
{
    int rows = m_sortFilter->rowCount();
    m_sortFilter->insertRows(rows, 1);

    QModelIndex source = m_featureModel->index(rows, 0);
    QModelIndex proxy = m_sortFilter->mapFromSource(source);

    if (!proxy.isValid())
    {
        qDebug() << Q_FUNC_INFO << "Inserted proxy index is invalid!";
        return;
    }

    ui->tableView->setCurrentIndex(proxy);
    ui->tableView->scrollTo(proxy);
    ui->tableView->edit(proxy);
}

void CharacterFeaturesForm::removeCharacterClass()
{
    QModelIndex index = ui->tableView->currentIndex();
    if (!index.isValid())
    {
        return;
    }

    ui->tableView->model()->removeRows(index.row(), 1);
}

void CharacterFeaturesForm::refresh()
{
    m_featureModel->revert();
}

void CharacterFeaturesForm::showEvent(QShowEvent *e)
{
    refresh();

    QWidget::showEvent(e);
}
